﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web.Security;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using FarPoint.Web.Spread;
using FarPoint.Web.Spread.Model;
using DQYT.HTDZ.BusinessService;
using DQYT.HTDZ.Common;
using DQYT.HTDZ.DBUtility;
using DQYT.HTDZ.Model;
using System.Globalization;
using DQYT.HTDZ.IDAL;
using Wuqi.Webdiyer;
using System.Text;
using System.IO;
using DQYT.HTDZ.BLL;




namespace DQYT.HTDZ.Web.Views.SJCJDB
{
    public partial class BasicData : System.Web.UI.Page
    {
        #region 本页面 传递及共用参数
        string StandardId = "";
        //string StandardName = "";
        string TableName = "";


        /*20100125张玉峰增加功能。如果用户每次要录入的是某个项目某个油田的数据，则在URL中添加以下参数：
         * FILTERCOLUMN=ID_PROJECT,ID_YQT&ID_PROJECT=16&ID_YQT=1
         * 如果本表的主键ID是类似于SQLSERVER的自增列，则在URL中添加以下参数：
         * AUTOCOLUMN=ID
         */
        public string m_FILTERCOLUMN = "";
        public Hashtable m_Filter = null;
        public string m_AUTOCOLUMN = "";


        public string m_CanImportData = "";//  =1 表示支持EXCEL数据导入功能

        #endregion

        #region 数据编辑参数设计
        /// <summary>
        /// 网格数据是否重绘
        /// </summary>
        public bool bIsPaint = false;
        /// <summary>
        /// 存入在提示信息表中最大的记录号
        /// </summary>
        private int iErrorMessageNum
        {
            get { return (int)ViewState["iErrorMessageNum"]; }
            set { ViewState["iErrorMessageNum"] = value; }
        }
        /// <summary>
        /// 存入主键
        /// </summary>
        private string sPriKey
        {
            get { return (string)ViewState["sPriKey"]; }
            set { ViewState["sPriKey"] = value; }
        }
        /// <summary>
        /// 存入删除的数据
        /// </summary>
        private DataTable sDelTab
        {
            get { return (DataTable)ViewState["sDelTab"]; }
            set { ViewState["sDelTab"] = value; }
        }
        /// <summary>
        /// 存入发生错误的错误信息的转换对应列表
        /// </summary>
        private Hashtable aErrorMessage_list
        {
            get { return (Hashtable)Session["aErrorMessage_list"]; }
            set { Session["aErrorMessage_list"] = value; }
        }
        /// <summary>
        /// 根据异常信息返回友好的提示信息
        /// </summary>
        /// <param name="sError"></param>
        /// <returns></returns>
        private string GetErrorMessage(string sError)
        {
            if (aErrorMessage_list != null)
            {
                Hashtable hasErrorMess = aErrorMessage_list;
                foreach (DictionaryEntry item in hasErrorMess)
                {
                    if (sError.IndexOf(item.Key.ToString().Trim()) != -1)
                        return item.Value.ToString();
                }
            }
            return "";
        }
        /// <summary>
        /// 存入发生错误的错误信息列表
        /// </summary>
        private void ErrorMessage_ini()
        {
            Hashtable hasErrorMess = new Hashtable();
            hasErrorMess["违反了 PRIMARY KEY 约束"] = "主键数据与已有的数据重复,请检查该行数据！";
            hasErrorMess["并发冲突"] = "并发冲突！";
            hasErrorMess["TABLE REFERENCE 约束"] = "表外键约束数据有误,外键值已被删除或不存在,请检查下拉数据源定义！";
            hasErrorMess["COLUMN REFERENCE 约束"] = "列约束数据有误,该键值已被其它记录数据引用，不可修改！";
            hasErrorMess["COLUMN FOREIGN KEY 约束"] = "列外键约束数据有误,外键值已被删除或不存在,请检查下拉数据源定义！";
            hasErrorMess["未将对象引用设置到对象的实例"] = "未将对象引用设置到对象的实例,请检查数据字典有关页面的数据源ID定义！";
            aErrorMessage_list = hasErrorMess;
        }

        //public void showMessage(string p_strShowMessage)
        //{
        //    this.RegisterStartupScript("01", "<script language=javascript> alert('" + p_strShowMessage + "')</script>");
        //}


        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {

          

            #region 代码实现
            // ReloadLogin(1, "2");

            m_CanImportData = Request.QueryString["CANIMPORTDATA"];
            StandardId = Request.QueryString["STANDARDID"];
            //TableName = Request.QueryString["table_code"];
            TableName = "BDDATESOURSE";
            //m_FILTERCOLUMN = Request.QueryString["FILTERCOLUMN"];
            m_FILTERCOLUMN = "SHZT";

            if (!string.IsNullOrEmpty(m_FILTERCOLUMN))
            {
                m_Filter = new Hashtable();
                string[] split = m_FILTERCOLUMN.Split(',');
                foreach (string str in split)
                {
                    string strValue = Request.QueryString[str];

                    m_Filter.Add(str, strValue);
                }
            }
            m_AUTOCOLUMN = Request.QueryString["AUTOCOLUMN"];

            //添加按钮后台事件
            //保存数据
            this.ImBtn_save.Click += new System.Web.UI.ImageClickEventHandler(this.ImBtn_save_Click);
            //this.ImBtn_save.Click += new System.EventHandler(this.ImBtn_save_Click);
            //取消
            this.ImBtn_cancle.Click += new System.Web.UI.ImageClickEventHandler(this.ImBtn_cancle_Click);
            //更新数据
            this.ImBtn_update.Click += new System.Web.UI.ImageClickEventHandler(this.ImBtn_update_Click);
            //删除数据
            this.ImBtn_delete.Click += new System.Web.UI.ImageClickEventHandler(this.ImBtn_delete_Click);
            //新加数据
            this.ImBtn_add.Click += new System.Web.UI.ImageClickEventHandler(this.ImBtn_add_Click);

            if (!this.IsPostBack)
            {

                this.Session.Add("curstatus", "0");           //当前状态 0为首次打开，1 为数据库配置 2为直接录入 3为文件导入 10 其他状态；
                this.Session.Add("resultsql", "");          //数据源配置返回的sql查询语句
                this.Session.Add("oppfields", "");          //本地表和服务器表对应字段
                this.Session.Add("srcdb", "");              //本地数据库连接信息
                this.Session.Add("table_code", HttpUtility.UrlDecode(this.Request.QueryString["table_code"].ToString()));

                //lblPath.Text = " 数据汇交>>数据库采集数据>> " + HttpUtility.UrlDecode(this.Request.QueryString["table_name"].ToString());
                //********************
                lblPath.Text = " 数据汇交>>数据库采集数据>> " + "BDDATESOURSE";
                if (this.Request.QueryString["table_code"] == null || this.Request.QueryString["table_code"].ToString() == "")
                    return;
                //***********
                else
                {
                    //获取当前待采集数据表
                    //ViewState["BDM"] = HttpUtility.UrlDecode(this.Request.QueryString["table_code"].ToString());
                    //***********************
                    ViewState["BDM"] = "BDDATESOURSE";
                    BDM.Value = ViewState["BDM"].ToString();
                    //获取当前表空数据
                    GetOraginData();

                    //如果传入参数"CANIMPORTDATA"等于1，就显示出数据导入功能
                    //if ((!string.IsNullOrEmpty(m_CanImportData)) && (m_CanImportData == "1"))
                    //{
                    divExcel.Visible = true;
                    ShowExcelTemplateURL();
                    //}
                    //else
                    //{
                    //    divExcel.Visible = false;
                    //}
                }
            }

            //操作方向
            //InitData();
            #endregion 代码实现
        }

     

        #region 新添加 主要是获取通过配置数据源来导入数据这个过程中用到的功能函数
        /// <summary>
        /// 获得用户code
        /// </summary>
        /// <returns></returns>
        public string GetUserCode()
        {
            #region
            string sUserCode = "";                        //用户代码code
            sUserCode = this.Session["UserName"].ToString();
            //int iUserID;                                //用户id

            ////获得当前用户代码
            //if (!string.IsNullOrEmpty(this.Session["UserID"].ToString()))
            //{
            //    iUserID = System.Convert.ToInt32(this.Session["UserID"].ToString());
            //    JrscSoft.DAL.USER dalUser = new JrscSoft.DAL.USER();
            //    JrscSoft.Model.USER modelUser = dalUser.GetModel(iUserID);
            //    if (modelUser != null)
            //    {
            //        sUserCode = modelUser.USER_NAME.Trim().ToString();
            //    }
            //}
            return sUserCode;
            #endregion
        }

        /// <summary>
        /// 显示模板链接
        /// </summary>
        private void ShowExcelTemplateURL()
        {
            #region
            string strExcelFile = BDM.Value + ".xls";
            if (string.IsNullOrEmpty(strExcelFile))
            {

            }
            else
            {
                hlExcelURL.NavigateUrl = "../DataFile/ExcelTemplate/" + strExcelFile;
            }
            #endregion
        }


        #region 垃圾
        /// <summary>
        /// 根据当前状态来判断 下来进行什么操作 初始化操作
        /// </summary>
        //private void InitData()
        //{
        //    //根据当前操作状态来进行下一步操作
        //    switch (this.Session["curstatus"].ToString())
        //    {
        //        case "0":

        //            break;
        //        case "1":
        //            //获得配置信息、连接数据库、获得datatable对象、把table传给控件、把状态设为“其他”
        //            DataTable dt = GetConfigDataSourceTable();
        //            //插入数据
        //            ConfigDataSourceReadData(dt);
        //            this.Session["curstatus"] = "10";
        //            break;
        //        case "2":

        //            break;
        //        case "3":

        //            break;
        //        default:
        //            break;

        //    }
        //}
        #endregion

        /// <summary>
        /// 获得通过配置数据源获得的table数据
        /// </summary>
        private DataTable GetConfigDataSourceTable()
        {
            #region
            //DataTable dt = new DataTable();
            DataSet ds = new DataSet();
            try
            {
                IConfigurature dbConf;
                string sResultSQL = this.Session["resultsql"].ToString();
                List<string> lstSrcDBInfo = (List<string>)this.Session["srcdb"];
                //List<ArrayList> lst2FieldInfo = (List<ArrayList>)this.Session["oppfields"];
                dbConf = ConnectionDB(lstSrcDBInfo[0].ToString());
                ds = dbConf.GetQueryResultDataSet(sResultSQL);
                ShowErrorInfo(ds.Tables["ErrorInfo"]);
                DeleteDB(lstSrcDBInfo[0].ToString());
                return ds.Tables[0];
            }
            catch (Exception ex)
            {
                AddErrorMess("数据提交有误！:" + ex.Message);
            }
            return ds.Tables[0];
            #endregion
        }
        /// <summary>
        /// 删除数据库临时文件
        /// </summary>
        /// <param name="DBType"></param>
        private void DeleteDB(string DBType)
        {
            #region
            string[] congInfo;

            try
            {
                switch (DBType)
                {
                    case "vpf":
                        congInfo = GetFileInfo();
                        File.Delete(congInfo[0].ToString());
                        break;
                    case "exl":
                        congInfo = GetFileInfo();
                        File.Delete(congInfo[0].ToString());
                        break;
                    case "mdb":
                        congInfo = GetFileInfo();
                        File.Delete(congInfo[0].ToString());
                        break;
                    default:
                        break;
                }

            }
            catch (Exception ex)
            {
            }
            #endregion
        }

        /// <summary>
        /// 连接数据库文件
        /// </summary>
        /// <returns>成功返回true，否则返回false</returns>
        private IConfigurature ConnectionDB(string DBType)
        {
            #region
            string[] congInfo;
            IConfigurature dbConf;

            try
            {
                switch (DBType)
                {
                    case "orl":
                        congInfo = GetDatabaseConInfo();
                        dbConf = new OracleConfigurature(congInfo, "");
                        return dbConf;
                    case "vpf":
                        congInfo = GetFileInfo();
                        dbConf = new VPFConfigurature(congInfo, "");
                        return dbConf;
                    case "exl":
                        congInfo = GetFileInfo();
                        dbConf = new ExcelConfigurature(congInfo);
                        return dbConf;
                    case "mdb":
                        congInfo = GetFileInfo();
                        dbConf = new AccessConfigurature(congInfo,"");
                        return dbConf;
                    default:
                        return null;
                }
            }
            catch (Exception ex)
            {
                JsAlert.Alert("连接数据库文件出错！");
                return null;
            }
            #endregion
        }

        /// <summary>
        /// 获得Oracle数据库连接信息
        /// </summary>
        /// <returns>返回字符串数组</returns>
        private string[] GetDatabaseConInfo()
        {
            #region
            string[] info = new string[6];
            List<string> lstSrcDBInfo = (List<string>)this.Session["srcdb"];

            for (int i = 0; i < lstSrcDBInfo.Count - 1; i++)
            {
                info[i] = lstSrcDBInfo[i + 1].ToString();
            }
            return info;
            #endregion
        }

        /// <summary>
        /// 获取数据库文件名字串数组
        /// </summary>
        /// <returns></returns>
        private string[] GetFileInfo()
        {
            #region
            string[] info = new string[2];
            List<string> lstSrcDBInfo = (List<string>)this.Session["srcdb"];

            info[0] = lstSrcDBInfo[1].ToString();
            info[1] = lstSrcDBInfo[2].ToString();
            return info;
            #endregion
        }

        /// <summary>
        /// 把从配置数据源中获得的数据读入到新表中
        /// </summary>
        /// <param name="dtConfigData"></param>
        private void ConfigDataSourceReadData(DataTable dtConfigData)
        {
            #region
            int iCurRow = 0;                                          //当前行号
            string sUserCode = GetUserCode();                        //用户代码code

            if ((dtConfigData == null) || (dtConfigData.Rows.Count == 0))
                return;
            //获取字段项列表
            DataTable dtfield = StandardService.GetInputFields(ViewState["BDM"].ToString());
            //int FdCnt = dtfield.Rows.Count;

            //获得字段对应信息
            List<ArrayList> lst2FieldInfo = (List<ArrayList>)this.Session["oppfields"];
            //获得一个没有数据的表
            DataTable dt = StandardService.GetInputTableNoData(ViewState["BDM"].ToString());
            foreach (DataRow drow in dtConfigData.Rows)
            {
                iCurRow = iCurRow + 1;
                DataRow newrow = dt.NewRow();
                //int iCurCol = 0;
                foreach (DataColumn col in dtConfigData.Columns)
                {
                    string strColName = col.ColumnName;//本地数据表列名
                    //iCurCol = iCurCol + 1;
                    if ((drow[strColName] != null) && (!string.IsNullOrEmpty(drow[strColName].ToString())))
                    {
                        //对应字段并赋值
                        for (int i = 0; i < lst2FieldInfo.Count; i++)
                        {
                            if (lst2FieldInfo[i][1].ToString().ToUpper() == strColName.ToUpper())
                            {
                                string dtColName = lst2FieldInfo[i][0].ToString();//服务器表列名
                                try
                                {
                                    newrow[dtColName.Trim().ToString()] = drow[strColName.ToUpper()].ToString().Trim(); ;
                                }
                                catch (Exception ex)
                                {
                                    AddErrorMess("第" + iCurRow.ToString() + "行，'" + dtColName.ToUpper() + "' 列，当前值：" + drow[strColName.ToUpper()].ToString() + "。错误信息：" + ex.Message.ToString());
                                }
                            }
                        }
                    }
                }
                ////添加三列固定列的值
                //string sDate = DateTime.Today.ToString("yyyyMMdd");
                //newrow["JZRQ"] = sDate;                         //加载日期应该是当前日期，将日期数据格式化一下
                //newrow["YHMC"] = sUserCode;                   //当前用户代码
                //newrow["SHZT"] = "0";                         //审核状态0为保存状态

                dt.Rows.Add(newrow);
            }
            SetFpSpread(dt);
            #endregion
        }

        #endregion

        #region 我新添加的事件

        protected void btnConfiguration_Click(object sender, EventArgs e)
        {
            JScript.OpenWebForm("ConfigDataSource.aspx");
        }
        #endregion

        /// <summary>
        /// 获取当前表已有数据
        /// </summary>
        protected void GetOraginData()
        {
            #region 代码实现
            //样式设置
            FpSpread1.CommandBar.Visible = false;
            FpSpread1.EditModeReplace = true;
            //数据操作模式
            //_EditGrid.Sheets[0].OperationMode = FarPoint.Web.Spread.OperationMode.SingleSelect;

            FpSpread1.Sheets[0].ColumnHeader.DefaultStyle.Font.Size = 9;
            FpSpread1.Sheets[0].DefaultStyle.Font.Size = 9;
            FpSpread1.Sheets[0].Rows.Default.Height = 10;

            //FpSpread1.Sheets[0].AlternatingRows[0].BackColor = System.Drawing.Color.Linen;
            //排序设置
            FpSpread1.Sheets[0].AllowSort = true;
            FpSpread1.Sheets[0].AllowColumnMove = true;

            //绑定数据
            SetData();

            //控件客户端事件添加
            //FpSpread1.Attributes["onDataChanged"] = "DataChanged()";
            //FpSpread1.Attributes["onSelectionChanged"] = "selectChanged()";
            //FpSpread1.Attributes["onEditStart"] = "spreadEditStart()";
            #endregion 代码实现
        }
        /// <summary>
        /// 数据绑定
        /// </summary>
        public void SetData()
        {
            #region 代码实现
            DataTable dt = null;

            //在此只提供带过滤功能的数据绑定
            //if ((m_Filter != null) && (m_Filter.Count > 0))
            //{
            //dt = StandardService.GetInputTableOraginData_Filter(ViewState["BDM"].ToString(), m_Filter);
            //}
            //else
            //{
            //    dt = StandardService.GetInputTableOraginData(ViewState["BDM"].ToString());
            //}
            dt = StandardService.GetInputTableOraginData_Filter(ViewState["BDM"].ToString(), m_Filter);

            SetFpSpread(dt);

            if ((!string.IsNullOrEmpty(m_CanImportData)) && (m_CanImportData == "1"))
            { }
            else
            {
                //初始化数据采集动态表单 先取消这个自动生成录入框的功能
                //InitInputFieldTextBox();
            }
            #endregion 代码实现
        }

        private void SetFpSpread(DataTable p_dt)
        {
            #region 代码实现
            //将数据和数据字典对应 
            if (this.PageSize.Text.ToString().Trim() == "")
                FpSpread1.Sheets[0].PageSize = 20;
            else
                FpSpread1.Sheets[0].PageSize = int.Parse(this.PageSize.Text);

            BindDataModel(p_dt);

            //数据分页绑定
            if (p_dt == null || p_dt.Rows.Count == 0)
            {
                FpSpread1.Sheets[0].AddRows(0, 1);
            }
            else
            {
                //数据统计
                this.AspNetPager1.RecordCount = p_dt.Rows.Count;
                SetPageData();
            }

            #endregion 代码实现

        }

        /// <summary>    
        /// 将数据和数据字典对应
        /// </summary>
        /// <param name="dtsource"></param>
        protected void BindDataModel(DataTable dt)
        {
            #region 代码实现
            //绑定数据
            FarPoint.Web.Spread.Model.DefaultSheetDataModel model = new FarPoint.Web.Spread.Model.DefaultSheetDataModel(dt);
            FpSpread1.Sheets[0].DataModel = model;
            //FpSpread1.Sheets[0].DataMember = "0";
            //FpSpread1.Sheets[0].ColumnHeader.RowCount = 1;


            //iErrorMessageNum = 0;//初始化提示信息的行数计数器
            //ErrorMessage_ini();//初始化错误信息

            ////设置删除的表session
            //if (ViewState["sDelTab"] == null)
            //    ViewState["sDelTab"] = dt.Clone();

            //hidPopField.Value = ",";

            ////获取字段项列表
            //DataTable dtfield = StandardService.GetInputFields(ViewState["BDM"].ToString());

            //if (dtfield == null || dtfield.Rows.Count == 0)
            //    return;
            //else 
            //{
            //    int iVisibleFieldCount = 0;
            //    int FdCnt = dtfield.Rows.Count;
            //    FieldCount.Value = FdCnt.ToString();
            //    for (int i = 0; i < FdCnt; i++)
            //    {

            //        //绑定对应数据列
            //        //model.SetModelDataColumn(i, dtfield.Rows[i]["fldname"].ToString().Trim());
            //        model.SetModelDataColumn(i, dtfield.Rows[i]["FIELD_CODE"].ToString().Trim());


            //        //设置列头宽度
            //        //if (dtfield.Rows[i]["columnwidth"].ToString().Trim() == "")
            //        //{
            //        //显示宽度
            //        if (dtfield.Rows[i]["FIELD_SHOWWIDTH"].ToString().Trim() == "")
            //        {
            //            if (dtfield.Rows[i]["FIELD_CODE"].ToString().Trim().Length < 6)
            //                FpSpread1.Sheets[0].Columns[i].Width = 70;
            //            else
            //                FpSpread1.Sheets[0].Columns[i].Width = 13 * dtfield.Rows[i]["FIELD_CODE"].ToString().Trim().Length;
            //        }
            //        else
            //        {
            //            int TitleLength = 12 * dtfield.Rows[i]["FIELD_CODE"].ToString().Trim().Length;
            //            int DataLength = int.Parse(dtfield.Rows[i]["FIELD_SHOWWIDTH"].ToString().Trim());
            //            if (TitleLength > DataLength)
            //            {
            //                FpSpread1.Sheets[0].Columns[i].Width = TitleLength;

            //            }
            //            else
            //            {
            //                FpSpread1.Sheets[0].Columns[i].Width = DataLength;
            //            }
            //        }
            //        //}
            //        //else
            //        //{
            //        //    FpSpread1.Sheets[0].Columns[i].Width = int.Parse(dtfield.Rows[i]["columnwidth"].ToString().Trim());
            //        //}

            //        //设置标题中的列名
            //        FpSpread1.Sheets[0].ColumnHeader.Cells[0, i].Value = dtfield.Rows[i]["FIELD_CODE"].ToString().Trim();

            //        //列标题字体显示设置
            //        FpSpread1.Sheets[0].ColumnHeader.Cells[0, i].Font.Bold = false;
            //        FpSpread1.Sheets[0].ColumnHeader.Cells[0, i].Font.Size = 9;

            //        string strPop = dtfield.Rows[i]["FIELD_POPWIN"].ToString();
            //        string strShow = dtfield.Rows[i]["FIELD_SHOW"].ToString().Trim();
            //        if (strShow == "0")
            //        {
            //            FpSpread1.Sheets[0].Columns[i].Visible = false;
            //        }
            //        else
            //        {
            //            FpSpread1.Sheets[0].Columns[i].Visible = true;
            //            iVisibleFieldCount++;

            //            if (!string.IsNullOrEmpty(strPop) && strPop.Trim().ToString() != "0")
            //            {
            //                hidPopField.Value += iVisibleFieldCount.ToString() + ":" + strPop + ",";

            //                for (int j = 0; j < dt.Rows.Count; j++)
            //                {
            //                    FpSpread1.Sheets[0].Cells[j, i].Font.Size = FontUnit.Parse("0.1");
            //                }
            //            }

            //        }


            //        ////添加字段单位
            //        //FpSpread1.Sheets[0].ColumnHeader.Cells[1, i].Value = dtfield.Rows[i]["unit"].ToString().Trim();

            //        //主键锁定不修改（已经屏蔽了不能修改，现在可以修改主键）
            //        if (dtfield.Rows[i]["FIELD_KEY"].ToString().Trim().ToUpper() == "1")
            //        {
            //            #region 代码实现
            //            FpSpread1.Sheets[0].ColumnHeader.Cells[0, i].Font.Bold = true;
            //            FpSpread1.Sheets[0].ColumnHeader.Cells[0, i].ForeColor = System.Drawing.Color.FromArgb(160, 82, 45);

            //            FpSpread1.Sheets[0].FrozenColumnCount = i + 1;
            //            //for (int j = 0; j < dt.Rows.Count; j++)
            //            //{
            //            //    FpSpread1.Sheets[0].Cells[j, i].Locked = true;
            //            //}
            //            sPriKey = sPriKey + dtfield.Rows[i]["FIELD_CODE"].ToString() + ",";
            //            #endregion 代码实现
            //        }

            //        //待计算字段
            //        //if (dtfield.Rows[i]["sfjs"].ToString().Trim() == "1")
            //        //{
            //        //    FpSpread1.Sheets[0].ColumnHeader.Cells[0, i].Font.Bold = true;
            //        //    FpSpread1.Sheets[0].ColumnHeader.Cells[0, i].ForeColor = System.Drawing.Color.FromArgb(128, 0, 128);
            //        //}
            //    }

            //    hidVisibleFieldCount.Value = iVisibleFieldCount.ToString();
            //    //根据字段类型设置单元格风格
            //    SetColumnCellStyle(dtfield);
            //}
            #endregion 代码实现
        }
        /// <summary>
        /// 初始化数据采集动态表单
        /// </summary>
        public void InitInputFieldTextBox()
        {
            #region 代码实现
            //构造采集界面
            DataTable dtfield = StandardService.GetInputFields(ViewState["BDM"].ToString());

            //行排列表单个数
            int BoxCount = 3;

            //如果数据为空
            string szModule = "<table  cellSpacing='0' cellPadding='0'  border='0' bordercolor='#b0c4de'  ID='ModuleList'>\r\n";

            //构造显示列表
            int BoxValue = 0;
            //spread 列
            int sCol = 0;
            for (int k = 0; k < dtfield.Rows.Count; k++)
            {
                //if (k % BoxCount == 0)
                if (BoxValue % BoxCount == 0)
                {
                    szModule += "  <tr align='left' height='26px'>\r\n";
                }

                //if (dtfield.Rows[k]["sfxs"].ToString().Trim() == "1")
                if (dtfield.Rows[k]["FIELD_SHOW"].ToString().ToUpper().Trim() == "1")
                {

                    szModule += " <td width='120' id='lab" + k.ToString() + "'  align='left' valign='middle'>";

                    //是否主键
                    string bprkey = "";
                    //主键标记为红色,获取主键列表
                    //if (dtfield.Rows[k]["ispkey"].ToString() == "1")
                    if (dtfield.Rows[k]["FIELD_KEY"].ToString().Trim().ToUpper() == "1")
                    {
                        szModule += "&nbsp;&nbsp;<font color='red'>" + dtfield.Rows[k]["FIELD_NAME"].ToString() + "</font>";

                        string PrKey = Pkey.Value;

                        if (PrKey == "")
                        {
                            PrKey = dtfield.Rows[k]["FIELD_CODE"].ToString();
                        }
                        else
                        {
                            PrKey = PrKey + "," + dtfield.Rows[k]["FIELD_CODE"].ToString();
                        }
                        Pkey.Value = PrKey;

                        bprkey = "disabled";
                    }
                    else
                        szModule += "&nbsp;&nbsp;" + dtfield.Rows[k]["FIELD_NAME"].ToString();

                    szModule += "</td>\r\n";

                    //根据不同采集数据类型,生成对应采集数据表单
                    szModule += "  <td width='180' id='txt" + k.ToString() + "'  align='left' valign='middle'>";

                    if (dtfield.Rows[k]["FIELD_DATASOURCE"].ToString() == "")
                    {
                        //控制表单输入字符长度
                        string MaxLength = "";
                        if (dtfield.Rows[k]["FIELD_LONG"].ToString() != "")
                        {
                            MaxLength = "maxlength=" + dtfield.Rows[k]["FIELD_LONG"].ToString();
                        }
                        string strPopWin = dtfield.Rows[k]["FIELD_POPWIN"].ToString();
                        //if (!string.IsNullOrEmpty(strPopWin))
                        if (!string.IsNullOrEmpty(strPopWin) && strPopWin.Trim().ToUpper() == "1")
                        {
                            //szModule += "&nbsp;<input id='Button_'" + k.ToString() + " type='button' value='打开' onclick='javascript:btnOpen(\"txt_" + k.ToString() + "\" ,\"" + sCol.ToString() + "\",\"" + strPopWin + "\");' /><input name='" + dtfield.Rows[k]["FIELD_CODE"].ToString() + "'  style='width:10px;height:18px' sfjs='" + dtfield.Rows[k]["sfjs"].ToString() + "' zdid='" + dtfield.Rows[k]["id"].ToString() + "'  id='txt_" + k.ToString() + "'  title='" + dtfield.Rows[k]["FIELD_NAME"].ToString() + "'  runat='server' type='hidden'  " + bprkey + "  " + MaxLength + " onkeyup='javascript:BindDataToGrid(this,\"" + sCol.ToString() + "\",\"" + dtfield.Rows[k]["FIELD_TYPE"].ToString() + "\");'/>";
                            szModule += "&nbsp;<input id='Button_'" + k.ToString() + " type='button' value='打开' onclick='javascript:btnOpen(\"txt_" + k.ToString() + "\" ,\"" + sCol.ToString() + "\",\"" + strPopWin + "\");' /><input name='" + dtfield.Rows[k]["FIELD_CODE"].ToString() + "'  style='width:10px;height:18px'  id='txt_" + k.ToString() + "'  title='" + dtfield.Rows[k]["FIELD_NAME"].ToString() + "'  runat='server' type='hidden'  " + bprkey + "  " + MaxLength + " onkeyup='javascript:BindDataToGrid(this,\"" + sCol.ToString() + "\",\"" + dtfield.Rows[k]["FIELD_TYPE"].ToString() + "\");'/>";
                            sCol++;
                        }
                        else
                        {

                            //控制表单输入字符限制,如数字型单元格,只允许输入小数点和数字
                            if (dtfield.Rows[k]["FIELD_TYPE"].ToString() == "N")
                            {
                                //szModule += "&nbsp;<input name='" + dtfield.Rows[k]["FIELD_CODE"].ToString() + "' style='width:150px;height:18px' sfjs='" + dtfield.Rows[k]["sfjs"].ToString() + "' zdid='" + dtfield.Rows[k]["id"].ToString() + "'  id='txt_" + k.ToString() + "'  title='" + dtfield.Rows[k]["fldname_cn"].ToString() + "'  runat='server' type='text'  " + bprkey + "  " + MaxLength + "  onkeyup='javascript:BindDataToGrid(this,\"" + sCol++.ToString() + "\",\"" + dtfield.Rows[k]["fldtype"].ToString() + "\");' onkeydown='onlyNum(this);'/>";
                                szModule += "&nbsp;<input name='" + dtfield.Rows[k]["FIELD_CODE"].ToString() + "' style='width:150px;height:18px'  id='txt_" + k.ToString() + "'  title='" + dtfield.Rows[k]["FIELD_NAME"].ToString() + "'  runat='server' type='text'  " + bprkey + "  " + MaxLength + "  onkeyup='javascript:BindDataToGrid(this,\"" + sCol++.ToString() + "\",\"" + dtfield.Rows[k]["FIELD_TYPE"].ToString() + "\");' onkeydown='onlyNum(this);'/>";
                            }
                            else
                            {
                                //szModule += "&nbsp;<input name='" + dtfield.Rows[k]["fldname"].ToString() + "'  style='width:150px;height:18px' sfjs='" + dtfield.Rows[k]["sfjs"].ToString() + "' zdid='" + dtfield.Rows[k]["id"].ToString() + "'  id='txt_" + k.ToString() + "'  title='" + dtfield.Rows[k]["fldname_cn"].ToString() + "'  runat='server' type='text'  " + bprkey + "  " + MaxLength + " onkeyup='javascript:BindDataToGrid(this,\"" + sCol++.ToString() + "\",\"" + dtfield.Rows[k]["fldtype"].ToString() + "\");'/>";
                                szModule += "&nbsp;<input name='" + dtfield.Rows[k]["FIELD_CODE"].ToString() + "'  style='width:150px;height:18px'  id='txt_" + k.ToString() + "'  title='" + dtfield.Rows[k]["FIELD_NAME"].ToString() + "'  runat='server' type='text'  " + bprkey + "  " + MaxLength + " onkeyup='javascript:BindDataToGrid(this,\"" + sCol++.ToString() + "\",\"" + dtfield.Rows[k]["FIELD_TYPE"].ToString() + "\");'/>";
                            }
                        }

                    }
                    else
                    {
                        string _fielddatasource = dtfield.Rows[k]["FIELD_DATASOURCE"].ToString();
                        if ((_fielddatasource.Length == 8) && (_fielddatasource.Substring(0, 8).ToUpper() == "CHECKBOX"))
                        {//<input id='Checkbox1' type="checkbox" runat=server />

                            //szModule += "&nbsp;<input name='" + dtfield.Rows[k]["fldname"].ToString() + "'  style='width:150px;height:20px' zdid='" + dtfield.Rows[k]["id"].ToString() + "' type='checkbox'  id='txt_" + k.ToString() + "'  title='" + dtfield.Rows[k]["fldname_cn"].ToString() + "' " + bprkey + "  runat='server' onclick='javascript:BindDataToGrid(this,\"" + sCol++.ToString() + "\");' />";
                            szModule += "&nbsp;<input name='" + dtfield.Rows[k]["FIELD_CODE"].ToString() + "'  style='width:150px;height:20px' type='checkbox'  id='txt_" + k.ToString() + "'  title='" + dtfield.Rows[k]["FIELD_CODE"].ToString() + "' " + bprkey + "  runat='server' onclick='javascript:BindDataToGrid(this,\"" + sCol++.ToString() + "\");' />";
                        }
                        else
                        {
                            //获取下拉选择列表
                            //szModule += "&nbsp;<select name='" + dtfield.Rows[k]["fldname"].ToString() + "'  style='width:150px;height:20px' zdid='" + dtfield.Rows[k]["id"].ToString() + "' id='txt_" + k.ToString() + "'  title='" + dtfield.Rows[k]["fldname_cn"].ToString() + "' " + bprkey + "  runat='server' onchange='javascript:BindDataToGrid(this,\"" + sCol++.ToString() + "\");'/>";
                            szModule += "&nbsp;<select name='" + dtfield.Rows[k]["FIELD_CODE"].ToString() + "'  style='width:150px;height:20px' id='txt_" + k.ToString() + "'  title='" + dtfield.Rows[k]["FIELD_NAME"].ToString() + "' " + bprkey + "  runat='server' onchange='javascript:BindDataToGrid(this,\"" + sCol++.ToString() + "\");'/>";

                            //获取采集对应数据源
                            DataTable ds = StandardService.GetInputFieldDataSource(dtfield.Rows[k]["FIELD_DATASOURCE"].ToString());

                            //构造下拉列表
                            for (int i = 0; i < ds.Rows.Count; i++)
                            {
                                szModule += "<option id='" + ds.Rows[i][0].ToString() + "' value='" + ds.Rows[i][1].ToString() + "'>" + ds.Rows[i][1].ToString() + "</option>";
                            }
                            szModule += "</select>";
                        }

                    }

                    szModule += "</td>\r\n";

                }


                //换行
                if ((BoxValue + 1) % BoxCount == 0)
                {
                    szModule += "</tr>\r\n";
                }
                if (dtfield.Rows[k]["FIELD_SHOW"].ToString().Trim() != "0")
                {
                    BoxValue = BoxValue + 1;
                }
            }

            szModule += "</table>\r\n";

            //记录下字段个数


            ltlModule.Text = szModule;


            #endregion 代码实现
        }
        /// <summary>
        /// 数据统计和页面翻页
        /// </summary>
        public void SetPageData()
        {
            #region
            AspNetPager1.CustomInfoHTML = "&nbsp;&nbsp;&nbsp;&nbsp;记录总数:<font color=\"blue\"><b>" + AspNetPager1.RecordCount.ToString() + "</b></font>";
            AspNetPager1.CustomInfoHTML += "&nbsp;&nbsp;总页数:<font color=\"blue\"><b>" + AspNetPager1.PageCount.ToString() + "</b></font>";
            AspNetPager1.CustomInfoHTML += "&nbsp;&nbsp;当前页:<font color=\"red\"><b>" + AspNetPager1.CurrentPageIndex.ToString() + "</b></font>&nbsp;&nbsp;&nbsp;&nbsp;";
            #endregion
        }
        /// <summary>
        /// 翻页功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ChangePage(object sender, Wuqi.Webdiyer.PageChangingEventArgs e)
        {
            #region
            AspNetPager1.CurrentPageIndex = e.NewPageIndex;
            FpSpread1.GotoPage(e.NewPageIndex - 1);
            //数据统计
            SetPageData();
            #endregion
        }
        /// <summary>
        /// 页数设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void PageSize_TextChanged(object sender, EventArgs e)
        {
            #region 代码实现
            if (PageSize.Text == "")
                return;
            else
            {
                try
                {
                    FpSpread1.Sheets[0].PageSize = (int.Parse(PageSize.Text));
                    FpSpread1.GotoPage(-1);
                    AspNetPager1.PageSize = FpSpread1.Sheets[0].PageSize;
                    //数据统计和翻页
                    SetPageData();
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                }
            }
            #endregion 代码实现
        }
        /// <summary>
        /// 单元格风格设置
        /// </summary>
        /// <param name="dtfield"></param>
        protected void SetColumnCellStyle(DataTable dtfield)
        {
            #region 代码实现
            int FdCnt = dtfield.Rows.Count;
            //根据字段类型设置单元格风格
            for (int i = 0; i < FdCnt; i++)
            {
                string _field = dtfield.Rows[i]["FIELD_TYPE"].ToString();

                FarPoint.Web.Spread.StyleInfo style = new FarPoint.Web.Spread.StyleInfo();

                switch (_field.ToUpper().Trim())
                {
                    //文本类
                    case "C":
                        {
                            TextCellType txt = new TextCellType();
                            txt.AllowWrap = false;
                            style.CellType = txt;
                            //style.CellType = new FarPoint.Web.Spread.TextCellType();
                            if (!string.IsNullOrEmpty(dtfield.Rows[i]["FIELD_POPWIN"].ToString().Trim()) && dtfield.Rows[i]["FIELD_POPWIN"].ToString().Trim() != "0")
                            {
                                style.Font.Size = FontUnit.Parse("0.1");
                            }
                            break;
                        }
                    //浮点类
                    case "N":
                        {
                            style.CellType = new FarPoint.Web.Spread.DoubleCellType(-1000000000.00000000, 1000000000.00000000, "超出范围或包含非数字字符");
                            break;
                        }
                    //日期类
                    case "D":
                        {
                            //采用日期验证
                            DateCellType dt = new DateCellType();

                            (dt as RegExpCellType).ValidationExpression = @"^((\d{2}(([02468][048])|([13579][26]))[\-\/]((((0?[13578])|(1[02]))[\-\/]((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/]((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/]((0?[1-9])|([1-2][0-9])))))|(\d{2}(([02468][1235679])|([13579][01345789]))[\-\/]((((0?[13578])|(1[02]))[\-\/]((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/]((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/]((0?[1-9])|(1[0-9])|(2[0-8]))))))(\s(((0?[0-9])|([1-2][0-3]))\:([0-5]?[0-9])((\s)|(\:([0-5]?[0-9])))))?$";
                            (dt as RegExpCellType).ErrorMessage = "输入日期有误,正确的格式如:2002-12-12 或 2002/12/12";

                            style.CellType = dt;

                            break;
                        }
                    //时间类
                    case "T":
                        {
                            TimeCellType dt = new TimeCellType();
                            style.CellType = dt;
                            break;
                        }

                }
                FpSpread1.Sheets[0].SetStyleInfo(-1, i, style);
            }
            //给下拉列表单元格赋值
            for (int i = 0; i < FdCnt; i++)
            {
                string _fielddatasource = dtfield.Rows[i]["FIELD_DATASOURCE"].ToString().Trim();

                if (_fielddatasource != "0" && _fielddatasource.Trim().ToString() != "")
                {
                    FarPoint.Web.Spread.StyleInfo style = new FarPoint.Web.Spread.StyleInfo();
                    if ((_fielddatasource.Length == 8) && (_fielddatasource.Substring(0, 8).ToUpper() == "CHECKBOX"))  //CHECKBOX,1,0
                    {
                        style.CellType = new FarPoint.Web.Spread.CheckBoxCellType();

                    }
                    else
                    {
                        //获取采集对应数据源
                        DataTable ds = StandardService.GetInputFieldDataSource(_fielddatasource);

                        if (ds.Columns.Count == 2)
                        {
                            string[] _values = new string[ds.Rows.Count];
                            string[] _items = new string[ds.Rows.Count];
                            for (int j = 0; j < ds.Rows.Count; j++)
                            {
                                _values[j] = Convert.ToString(ds.Rows[j].ItemArray[1]).Trim();
                                _items[j] = Convert.ToString(ds.Rows[j].ItemArray[0]).Trim();
                            }

                            style.CellType = new FarPoint.Web.Spread.ComboBoxCellType(_values, _items);

                        }
                    }
                    FpSpread1.Sheets[0].SetStyleInfo(-1, i, style);    //Apply the style 
                }
            }
            #endregion 代码实现
        }

        #region 扩展控件
        /// <summary>
        /// 扩展验证日期单元格 
        /// </summary>
        class DateCellType : FarPoint.Web.Spread.RegExpCellType
        {
            public override string Format(object value)
            {
                //获取年月日,去掉时间
                string sVal = value.ToString();
                string[] strA = sVal.Split(new char[1] { ' ' });
                return strA[0].ToString();
            }


        }
        /// <summary>
        /// 扩展验证日期单元格 
        /// </summary>
        class TimeCellType : FarPoint.Web.Spread.RegExpCellType
        {
            public override string Format(object value)
            {
                //获取年月日时间
                string sVal = value.ToString();
                return sVal;
            }
        }
        #endregion 扩展控件

        /// <summary>
        /// FpSpread1事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void FpSpread1_SaveOrLoadSheetState(object sender, FarPoint.Web.Spread.SheetViewStateEventArgs e)
        {
            #region
            if (e.IsSave)
            {
                FpSpread1.Page.Session["ViewState"] = e.SheetView.SaveViewState();
            }
            else
            {
                e.SheetView.LoadViewState(FpSpread1.Page.Session["ViewState"]);
            }
            e.Handled = true;
            #endregion
        }
        /// <summary>
        /// 获取待计算字段参数,构建参数数据计算界面
        /// </summary>
        /// <param name="FieldParameters"></param>
        /// <returns></returns>
        [System.Web.Services.WebMethod]
        public static string GetDataFieldFactor(string FieldParameters)
        {
            #region 代码实现
            return "";
            /*
            string[] FieldParameter = FieldParameters.Split(',');
            //计算结果
            DataTable dt = BaseDataInput.GetDataFieldFactor(FieldParameter[1].ToString());

            if (dt == null || dt.Rows.Count == 0)
                return "";
            else
            {
                string RowCount = dt.Rows.Count.ToString();
                //如果数据为空
                string szModule = "<table   border='1' bordercolor='#b0c4de' cellpadding='0' cellspacing='0' style='height:100%'>";

                //标题
                szModule += "<tr bgcolor='#eef8ff'>";
                szModule += "<td style='height:30px;font-weight:bold'  colspan='4'>" + FieldParameter[0].ToString() + "计算</td>";
                szModule += "</tr>";

                //参数标题
                szModule += "<tr bgcolor='#eef8ff' >";
                szModule += "<td style='width:100px'>参数名称</td>";
                szModule += "<td style='width:100px'>参数单位</td>";
                szModule += "<td style='width:100px'>参数范围</td>";
                szModule += "<td style='width:100px'>参数赋值</td>";
                szModule += "</tr>";
                //构造显示列表
                for (int k = 0; k < dt.Rows.Count; k++)
                {

                    szModule += "<tr>";
                    szModule += "<td style='width:100px'>" + dt.Rows[k]["zbmc"].ToString() + "</td>";
                    szModule += "<td style='width:100px'>" + dt.Rows[k]["zbdw"].ToString() + "</td>";
                    szModule += "<td style='width:100px'>" + dt.Rows[k]["zbfw"].ToString() + "</td>";
                    szModule += "<td>";
                    szModule += "<input type='text' id='zb_lab_" + k.ToString() + "'  name='" + dt.Rows[k]["zbdm"].ToString() + "' title='" + dt.Rows[k]["zbmc"].ToString() + "'    value='' style='width:120px' onkeydown='onlyNum(this);'>";
                    szModule += "</td>";
                    szModule += "</tr>";
                }
                szModule += "<tr>";
                szModule += "<td colspan='4' align='center'>";
                //szModule += "<ext:Button ID='btnComunicateInClient' runat='server' Text='计算' Icon='Calculator'><Listeners><Click Handler='btnCancel()' /></Listeners></ext:Button>";

                szModule += "<input type='button' name='Confrim' onclick='btnConfrim(\"" + RowCount + "\",\"" + FieldParameter[1].ToString() + "\");' value='计算'/ style='width:50px'>&nbsp;&nbsp;&nbsp;<input type='button' name='Cancel' onclick='btnCancel();' value='取消' style='width:50px'/>";
                szModule += "</td>";
                szModule += "</tr>";

                szModule += "</table>";

                return szModule;
            }
             */
            #endregion 代码实现
        }

        [System.Web.Services.WebMethod]
        public static string ComunicateDataField(string FieldParameters)
        {
            return "";
            /*
            //计算结果
            string ResultValue = BaseDataInput.ComunicateDataField(FieldParameters);

            return ResultValue;  */

        }

        /// <summary>
        /// 更新已修改数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //private void ImBtn_save_Click(object sender, System.EventArgs e)
        //{
        //    DataSave();
        //}
        private void DataSave()
        {
            #region 代码实现
            bool IsNewData = false;
            int iNewMaxID = 0;
            FarPoint.Web.Spread.Model.DefaultSheetDataModel model = (FarPoint.Web.Spread.Model.DefaultSheetDataModel)FpSpread1.Sheets[0].DataModel;
            //获取当前表格数据源
            System.Data.DataSet ds = (System.Data.DataSet)model.DataSource;
            DataTable dt_copy = new DataTable();
            DataTable dt;

            DataTable DtChanges_temp = null;

            ArrayList aErrorNum_temp = new ArrayList();
            ArrayList aErrorMess_temp = new ArrayList();
            ArrayList aErrorSate_temp = new ArrayList();

            try
            {
                //保存改变数据，但是不是提交到数据库
                this.FpSpread1.SaveChanges();

                Session["ViewState"] = this.FpSpread1.Sheets[0].SaveViewState();

                //为设置记录颜色（修改：黄；增加：绿；错误：红），保持原始的记录状态的数据表
                dt = ds.Tables[0];
                //dt_copy = dt.Copy;
                DataTable DtChanges = dt.GetChanges();
 
                //检测数据表中的逻辑错误
                if (!CheckLogic(this.FpSpread1))
                {
                    return;
                }

                DtChanges_temp = DtChanges;
                if (DtChanges == null)
                    return;
                else if (DtChanges.Rows.Count > 0)
                {
                    //更新数据
                    bool btrue = false;


                    bool isSuccess = StandardService.TransUpdateTable(dt, ViewState["BDM"].ToString());
                    if (!isSuccess)
                    {
                        ////回滚数据
                       
                        //AddErrorMess("数据提交失败！");
                        //return;
                    }


                    //if ((m_Filter != null) && (m_Filter.Count > 0))
                    //{
                    //btrue = StandardService.UpdateTable_Filter(dt, ViewState["BDM"].ToString(), m_Filter, m_AUTOCOLUMN);
                    //    btrue = StandardService.UpdateTable_Filter(dt_copy, ViewState["BDM"].ToString(), m_Filter, m_AUTOCOLUMN, this.chkIgnoreKeyConflict.Checked);
                    //}
                    //else if (!string.IsNullOrEmpty(m_AUTOCOLUMN))
                    //{
                    //    //btrue = StandardService.UpdateTable_Filter(dt, ViewState["BDM"].ToString(), m_Filter, m_AUTOCOLUMN);
                    //    btrue = StandardService.UpdateTable_Filter(dt_copy, ViewState["BDM"].ToString(), m_Filter, m_AUTOCOLUMN);
                    //}
                    //else
                    //{
                    //    //btrue = StandardService.UpdateTable(dt, ViewState["BDM"].ToString());
                    //    btrue = StandardService.UpdateTable(dt_copy, ViewState["BDM"].ToString());
                    //}
                    //if (btrue)
                    //{

                    //    //将删除的数据放入删除的数据Sheet中
                    //    //ShowDelRecordState(DtChanges);                                      

                    //    ds.AcceptChanges();
                    //    IsNewData = false;                  //重新赋值，以防下面的代码出错，误删除记录
                    //    this.AspNetPager1.RecordCount = FpSpread1.Rows.Count;
                    //    SetPageData();
                    //    GetOraginData();
                    //    this.FpSpread_Error.Sheets[0].Rows.Add(iErrorMessageNum, 1);
                    //    this.FpSpread_Error.Sheets[0].SetValue(iErrorMessageNum, 0, "数据提交成功！");
                    //}

                    //else
                    //{
                    //    //删除刚才添加到审核表中的记录
                    //    if (IsNewData == true)
                    //    {
                    //        //JrscSoft.BLL.STRUCTDATA_AUDIT bllStructData_Audit1 = new JrscSoft.BLL.STRUCTDATA_AUDIT();
                    //        //bllStructData_Audit1.Delete(iNewMaxID);
                    //        //JrscSoft.BLL.SDA_WELL bllSDA_Well = new JrscSoft.BLL.SDA_WELL();
                    //        //bllSDA_Well.Delete(iNewMaxID);
                    //    }
                    //    this.FpSpread_Error.Sheets[0].Rows.Add(iErrorMessageNum, 1);
                    //    this.FpSpread_Error.Sheets[0].SetValue(iErrorMessageNum, 0, "数据提交有误！");
                    //}
                }
                FpSpread1.SaveChanges();
                AspNetPager1.RecordCount = FpSpread1.Rows.Count;
                AspNetPager1.CurrentPageIndex = AspNetPager1.PageCount;
                SetPageData();
                FpSpread1.GotoPage(AspNetPager1.CurrentPageIndex);

            }
            catch (Exception ex)
            {
                AddErrorMess("数据提交有误！:" + ex.Message);
                //删除刚才添加到审核表中的记录
                if (IsNewData == true)
                {
                    //JrscSoft.BLL.STRUCTDATA_AUDIT bllStructData_Audit = new JrscSoft.BLL.STRUCTDATA_AUDIT();
                    //bllStructData_Audit.Delete(iNewMaxID);
                    //JrscSoft.BLL.SDA_WELL bllSDA_Well = new JrscSoft.BLL.SDA_WELL();
                    //bllSDA_Well.Delete(iNewMaxID);
                }
            }

            for (int iCount = 0; iCount < aErrorNum_temp.Count; iCount++)
            {
                string sError = "";
                if (aErrorMess_temp[iCount].ToString().Trim() != "update_ok")
                {
                    sError = GetErrorMessage(aErrorMess_temp[iCount].ToString().Trim());
                    if (sError.Trim() != "") aErrorMess_temp[iCount] = sError;
                }
            }
            //保存时已设置颜色不要重画
            bIsPaint = true;
            #endregion 代码实现
        }

        ///// <summary>
        ///// 获得用户的组id
        ///// </summary>
        ///// <returns></returns>
        //private int GetGroupID()
        //{
        //    #region
        //    try
        //    {
        //        int iUserID = Convert.ToInt32(this.Session["UserID"].ToString());

        //        JrscSoft.BLL.USER bllUser = new JrscSoft.BLL.USER();
        //        JrscSoft.Model.USER user = bllUser.GetModel(iUserID);
        //        if (user != null)
        //        {
        //            return Convert.ToInt32(user.COMPANY);
        //        }
        //        else
        //        {
        //            return -1;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        System.Console.WriteLine(ex.Message.ToString());
        //        return -1;


        //    }
        //    #endregion
        //}

 

        /// <summary>
        /// 操作行按钮事件
        /// </summary>
        /// <param name="sButtonName"></param>
        private void ButtonClick(string sButtonName)
        {
            #region 代码实现
            try
            {
                System.Data.DataSet ds = (System.Data.DataSet)this.FpSpread1.ActiveSheetView.DataSource;
                DataTable dt = ds.Tables[0];
              
                //数据更新
                if (sButtonName == "update")
                {
                    FpSpread1.SaveChanges();
                    //检测数据表中的逻辑错误
                    if (!CheckLogic(FpSpread1))
                        return;
                    else
                    {
                        ImBtn_update.Enabled = false;
                        ImBtn_cancle.Enabled = false;
                    }
                    FpSpread1.SaveChanges();
                    AspNetPager1.RecordCount = FpSpread1.Rows.Count;
                    AspNetPager1.CurrentPageIndex = AspNetPager1.PageCount;
                    SetPageData();
                    FpSpread1.GotoPage(AspNetPager1.CurrentPageIndex);
                }
                //数据取消
                else if (sButtonName == "cancle")
                {
                    FpSpread1.CancelEdit();

                    if (ImBtn_add.Enabled == false)
                        FpSpread1.Rows.Remove(FpSpread1.Rows.Count - 1, 1);

                    if (FpSpread1.Sheets[0].RowCount > 20)
                    {
                        //SetButtonState("0,0,0,1,1,0,0,0,0,0,1,1,0");
                    }
                    else
                    {
                        //SetButtonState("0,0,0,1,1,0,0,0,0,0,0,1,0");
                    }
                    //SetPreNextButtonState();
                }
                //数据添加
                else if (sButtonName == "add")
                {
                    FarPoint.Web.Spread.Model.DefaultSheetDataModel dm = (FarPoint.Web.Spread.Model.DefaultSheetDataModel)FpSpread1.ActiveSheetView.DataModel;
                    dm.AddRow();
                    int num = FpSpread1.Sheets[0].RowCount;

                    ImBtn_cancle.Enabled = true;
                    ImBtn_update.Enabled = true;
                    ImBtn_save.Enabled = true;

                    int iPage = FpSpread1.Sheets[0].RowCount + 1;
                    int iPages = (int)(iPage / (FpSpread1.Sheets[0].PageSize));
                    FpSpread1.GotoPage(iPages);
                    //if (iPages == 0)
                    //    this.TextBox1.Text = "1";
                    //else
                    //    this.TextBox1.Text = iPages.ToString();
                    //SetPreNextButtonState();
                }
                //删除数据
                else if (sButtonName == "del")
                {
                    FpSpread1.SaveChanges();
                    //客户端获取当前所选行和行数,进行批量删除操作
                    string[] Values = this.Selectrows.Value.Split('#');

                    int iSatartRow, iRowCount;
                    if (AspNetPager1.CurrentPageIndex == AspNetPager1.PageCount & AspNetPager1.PageCount != 1)
                    {
                        //iSatartRow = AspNetPager1.RecordCount-(AspNetPager1.PageSize - int.Parse(Values[0]));
                        iSatartRow = AspNetPager1.CurrentPageIndex * AspNetPager1.PageSize - (AspNetPager1.PageSize - AspNetPager1.RecordCount % AspNetPager1.PageSize) - (AspNetPager1.PageSize - int.Parse(Values[0]));
                    }
                    else
                    {
                        iSatartRow = int.Parse(Values[0]) + AspNetPager1.PageSize * (AspNetPager1.CurrentPageIndex - 1);
                    }
                    iRowCount = int.Parse(Values[2]);
                    FpSpread1.Sheets[0].RemoveRows(iSatartRow, iRowCount);
                    if (AspNetPager1.CurrentPageIndex == AspNetPager1.PageCount)
                    {
                        ViewState["iSatartRow"] = AspNetPager1.RecordCount - (AspNetPager1.PageSize - int.Parse(Values[0]));
                    }
                    else
                    {
                        ViewState["iSatartRow"] = int.Parse(Values[0]) + AspNetPager1.PageSize * (AspNetPager1.CurrentPageIndex - 1);
                    }
                    ViewState["iRowCount"] = int.Parse(Values[2]);

                    FpSpread1.SaveChanges();

                    AspNetPager1.RecordCount = AspNetPager1.RecordCount - int.Parse(Values[2]);
                    SetPageData();

                    ImBtn_update.Enabled = false;
                    ImBtn_cancle.Enabled = false;
                    ImBtn_save.Enabled = true;

                    //SetPreNextButtonState();
                    //保存删除记录
                    //ShowDelRecordState(dt);
                }
               
            }
            catch (System.Exception ex)
            {
                AddErrorMess(ex.Message);
            }

            #endregion 代码实现
        }
        /// <summary>
        /// 数据逻辑检查
        /// </summary>
        /// <param name="Spread"></param>
        /// <returns></returns>
        private bool CheckLogic(FpSpread Spread)
        {
            #region 代码实现
            //清空错误的计算器
            iErrorMessageNum = 0;
            //清空错误表
            this.FpSpread_Error.Sheets[0].Rows.Remove(0, this.FpSpread_Error.Sheets[0].Rows.Count);

            System.Data.DataSet ds = (System.Data.DataSet)Spread.ActiveSheetView.DataSource;
            DataTable dt = ds.Tables[0];
            string sTemp;
            bool bReturn = true;
            int i = 0;

            ////获得当前用户代码
            //string sUserCode = GetUserCode();                        //用户代码code,暂时屏蔽
            ////在此给三个固定列赋值
            //for (int iRows = 0; iRows < dt.Rows.Count; iRows++)
            //{
            //    try
            //    {
            //        //添加三列固定列的值
            //        string sDate = DateTime.Today.ToString("yyyyMMdd");
            //        dt.Rows[iRows]["JZRQ"] = sDate;                 //加载日期应该是当前日期，将日期数据格式化一下
            //        dt.Rows[iRows]["YHMC"] = sUserCode;             //当前用户代码
            //        dt.Rows[iRows]["SHZT"] = "1";                   //审核状态1为提交状态
            //    }
            //    catch (Exception ex)
            //    {
            //        System.Console.WriteLine(ex.Message.ToString());
            //    }
            //}

            //获取效验列
            DataTable dtfield = StandardService.GetInputFields(ViewState["BDM"].ToString());

            int cnt = dtfield.Rows.Count;

            Hashtable hs_ChechNullColumn = new Hashtable();
            Hashtable hs_ChechLogicColumn = new Hashtable();
            Hashtable hs_ChechUniqueColumn = new Hashtable();
            //是否允许空,获取待检测字段列表
            for (int k = 0; k < cnt; k++)
            {
                //是否允许为空0为空 1不为空
                if (dtfield.Rows[k]["FIELD_NULL"].ToString().Trim() == "1")
                {
                    hs_ChechNullColumn[dtfield.Rows[k]["FIELD_CODE"].ToString().Trim()] = dtfield.Rows[k]["FIELD_CODE"].ToString().Trim();
                }
                //是否唯一
                if (dtfield.Rows[k]["FIELD_UNIQUE"].ToString().Trim() == "1")
                {
                    hs_ChechUniqueColumn[dtfield.Rows[k]["FIELD_CODE"].ToString().Trim()] = dtfield.Rows[k]["FIELD_CODE"].ToString().Trim();
                }
            }



            //检测逻辑关系
            foreach (DataRow drow in dt.Rows)
            {

                i++;
                System.Data.DataRowState rs = drow.RowState;

                if (rs == DataRowState.Deleted)
                {
                    i--;
                    continue;
                }
                else if (rs == DataRowState.Added || rs == DataRowState.Modified)
                {
                    //检测是否为空
                    foreach (DictionaryEntry aChechColumn in hs_ChechNullColumn)
                    {
                        if (drow[aChechColumn.Key.ToString().Trim()].ToString().Trim().Length == 0)
                        {
                            if (aChechColumn.Key.ToString().Trim() != "ID" && aChechColumn.Key.ToString().Trim() != "SDAID")
                            {
                                sTemp = aChechColumn.Value.ToString();
                                sTemp = "第" + Convert.ToString(i) + "行字段'" + sTemp + "'值不能为空";
                                AddErrorMess(sTemp);
                                bReturn = false;
                            }
                        }
                    }

                    foreach (DictionaryEntry aUkCol in hs_ChechUniqueColumn)
                    {
                        string strCol = aUkCol.Key.ToString().Trim();
                        if (dt.Select(strCol + "='" + drow[strCol].ToString() + "'").Length > 1)
                        {
                            string strError = "第" + Convert.ToString(i) + "行字段'" + aUkCol.Value.ToString() + "'值重复";
                            AddErrorMess(strError);
                            bReturn = false;
                        }
                    }
                }
            }
            if (bReturn)
            {
                AddErrorMess("数据检测通过！");
            }
            return bReturn;
            #endregion 代码实现

        }

        /// <summary>
        /// 追加单条记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ImBtn_add_Click(object sender, System.EventArgs e)
        {
            ButtonClick("add");
        }
        /// <summary>
        /// 更新修改数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ImBtn_update_Click(object sender, System.EventArgs e)
        {
            ButtonClick("update");
        }
        /// <summary>
        /// 取消修改数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ImBtn_cancle_Click(object sender, System.EventArgs e)
        {
            ButtonClick("cancle");
        }
        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ImBtn_delete_Click(object sender, System.EventArgs e)
        {
            ButtonClick("del");
        }
    
        /// <summary>
        /// 添加错误信息
        /// </summary>
        /// <param name="sMessage"></param>
        public void AddErrorMess(string sMessage)
        {
            this.FloatPanel.Visible = true;
            this.FpSpread_Error.Sheets[0].Rows.Add(iErrorMessageNum, 1);
            FpSpread_Error.Sheets[0].SetValue(iErrorMessageNum, 0, sMessage);
            FpSpread_Error.Sheets[0].Cells[iErrorMessageNum, 0].Locked = true;
            iErrorMessageNum = iErrorMessageNum + 1;
            this.FpSpread_Error.Sheets[0].PageSize = iErrorMessageNum;
        }


        /// <summary>
        /// 读取本地文件数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnReadData_Click(object sender, EventArgs e)
        {
            #region 代码实现
            //获得当前用户代码
            string sUserCode = GetUserCode();                        //用户代码code

            string sFileName = FileUpload1.FileName.Trim().ToLower();
            if (sFileName.Length > 4)
            {
                string sXlsx = sFileName.Substring(sFileName.Length - 5);
                string sXls = sFileName.Substring(sFileName.Length - 4);
                if (sXlsx != ".xlsx" && sXls != ".xls")
                {
                    JScript.Alert(this.Page, "在此只能上传由我们提供的Excel模板文件数据！");
                    return;
                }
            }
            else
            {
                JScript.Alert(this.Page, "文件错误！");
                return;
            }

            if (string.IsNullOrEmpty(FileUpload1.FileName.Trim()))
            { }
            else
            {
                try
                {
                    ProcYC_File pf = new ProcYC_File();
                    pf.m_AccessoryUpload = this.FileUpload1;

                    DataTable dtExcel = pf.GetDataTableFromExcelFile();
                    if ((dtExcel == null) || (dtExcel.Rows.Count == 0))
                        return;
                    /////////////////////////////////////////////////////////////////
                    //获取字段项列表
                    DataTable dtfield = StandardService.GetInputFields(ViewState["BDM"].ToString());
                    int FdCnt = dtfield.Rows.Count;

                    Hashtable htDM = new Hashtable();

                    //
                    for (int i = 0; i < FdCnt; i++)
                    {
                        string _fielddatasource = dtfield.Rows[i]["FIELD_DATASOURCE"].ToString().Trim();
                        string _fieldName = dtfield.Rows[i]["FIELD_CODE"].ToString().Trim();

                        if (_fielddatasource != "0" && _fielddatasource.Trim().ToString() != "")
                        {
                            if ((_fielddatasource.Length == 8) && (_fielddatasource.Substring(0, 8).ToUpper() == "CHECKBOX"))  //CHECKBOX,1,0
                            { }
                            else
                            {
                                //获取采集对应数据源
                                DataTable ds = StandardService.GetInputFieldDataSource(_fielddatasource);
                                htDM.Add(_fieldName, ds);
                            }

                        }
                    }


                    ////////////////////////////////////////////////////////////////
                    int iCurRow = 0;
                    DataTable dt = StandardService.GetInputTableNoData(ViewState["BDM"].ToString());

                    foreach (DataRow drow in dtExcel.Rows)
                    {
                        iCurRow = iCurRow + 1;
                        DataRow newrow = dt.NewRow();
                        foreach (DataColumn col in dtExcel.Columns)
                        {
                            string strColName = col.ColumnName;
                            if ((drow[strColName] != null) && (!string.IsNullOrEmpty(drow[strColName].ToString())))
                            {
                                if (htDM[strColName] != null)
                                {
                                    DataTable dtDM = (DataTable)htDM[strColName];
                                    foreach (DataRow rDM in dtDM.Rows)
                                    {
                                        if (rDM[1].ToString() == drow[strColName].ToString())
                                        {
                                            newrow[strColName] = rDM[0];
                                            break;
                                        }


                                    }
                                }
                                else
                                {
                                    try
                                    {
                                        //给单元格赋值
                                        newrow[strColName.Trim().ToUpper().ToString()] = drow[strColName.ToUpper()].ToString().Trim();
                                    }
                                    catch (Exception ex)
                                    {
                                        //System.Console.WriteLine(ex.ToString());
                                        AddErrorMess("第" + iCurRow.ToString() + "行，'" + strColName.ToUpper() + "' 列，当前值：" + drow[strColName.ToUpper()].ToString() + "。错误信息：" + ex.Message.ToString());
                                    }
                                }
                            }
                        }
                        //添加三列固定列的值
                        string sDate = DateTime.Today.ToString("yyyyMMdd");
                        newrow["JZRQ"] = sDate;                         //加载日期应该是当前日期，将日期数据格式化一下
                        newrow["YHMC"] = sUserCode;                   //当前用户代码
                        newrow["SHZT"] = "0";                         //审核状态0为保存状态

                        dt.Rows.Add(newrow);
                    }
                    SetFpSpread(dt);
                }
                catch (Exception ex)
                {
                    AddErrorMess("请检查文件格式是否符合规范.错误信息：" + ex.Message.ToString());
                    //JScript.Alert(this.Page, ex.Message.ToString());
                }

            }
            #endregion 代码实现
        }

        protected void LinkButton1_Click(object sender, System.EventArgs e)
        {
            try
            {
                FpSpread spread = FpSpread1;
                //spread.SaveChanges();
                string data = "";
                data = hidKid.Value;
                if (data.Trim().Length == 0 || data == "data") return;

                int countcols = 1;
                int maxcols = 1;
                int countrows = 1;
                //
                //int startpos = 0;
                //
                //int length = 0;
                int col;
                int row;
                int startrow = spread.Sheets[0].RowCount;

                int startcol = 0;//spread.Sheets[0].ActiveColumn;
                for (int i = 0; i < data.Length; i++)
                {
                    string split = data.Substring(i, 1);
                    switch (split)
                    {
                        case "\r":
                            if (countcols > maxcols)
                                maxcols = countcols;
                            countcols = 0;
                            if (i < data.Length - 3)
                                countrows += 1;
                            break;
                        case "\t":
                            countcols += 1;
                            break;
                    }
                }

                countcols = maxcols;
                //修改了如果第一行是空行的判断
                if (spread.Rows.Count == 0)//? (Spread.IsBlankRow)
                {
                    //startrow--;
                    spread.Rows.Add(spread.Rows.Count, countrows);
                }
                else
                {
                    if (spread.Sheets[0].Cells[startrow - 1, 0].Text.ToString().Trim() == "")
                    {
                        startrow = startrow - 1;
                        spread.Rows.Add(spread.Rows.Count, countrows - 1);
                    }
                    else
                    {
                        spread.Rows.Add(spread.Rows.Count, countrows);
                    }
                }
                //startpos = 0;
                int iVisibleCols = 0;
                string data1 = data.Replace("\r\n", "\r");
                data1 = data1.Replace("\n", "\r");
                data = data1;
                string[] datas = data.Split('\r');
                //string s = "";
                for (row = startrow; row < startrow + countrows; row++)
                {
                    for (col = startcol; col < startcol + countcols; col++)
                    {
                        if (col >= spread.Sheets[0].Columns.Count) break;
                        if (datas[row - startrow].Trim().Length == 0) break;
                        while (!spread.Sheets[0].Columns[iVisibleCols].Visible)
                        {
                            iVisibleCols++;
                        }
                        string[] rows = datas[row - startrow].Split('\t');
                        if (col >= rows.Length) break;

                        try
                        {
                            spread.Sheets[0].Cells[row, iVisibleCols].Text = rows[col];
                        }
                        catch (Exception ex)
                        {
                            int r = row + 1;
                            int c = col + 1;
                            string strMessage = "第" + r + "行" + " 第" + c + "列 " + "数据有问题,具体错误如下 ：" + ex.Message;
                            //System.Console.WriteLine(strMessage);
                            AddErrorMess(strMessage);
                            //return;
                        }
                        iVisibleCols++;
                        //}
                    }
                    iVisibleCols = 0;
                }

                //ImBtn_add.Enabled = false;
                //ImBtn_pasteadd.Enabled = false;
                ImBtn_cancle.Enabled = true;

                int iPage = spread.Sheets[0].RowCount + 1;
                int iPages = (int)(iPage / (spread.Sheets[0].PageSize));
                spread.GotoPage(iPages);
                //?  SetPreNextButtonState();
            }
            catch (Exception ex1)
            {
                //System.Console.WriteLine(ex1.ToString());
                AddErrorMess(ex1.ToString());
            }
        }

        //根据配置数据源得到的信息插入数据到数据库
        protected void btnRun_Click(object sender, EventArgs e)
        {
            DataTable dt = GetConfigDataSourceTable();
            //插入数据
            ConfigDataSourceReadData(dt);
            this.Session["curstatus"] = "10";
        }
        /// <summary>
        /// 把从vfp和xls文件转换过了数据时出的错误信息显示出来
        /// </summary>
        /// <param name="dt">存储错误信息的表 （错误行数，错误列数）</param>
        private void ShowErrorInfo(System.Data.DataTable dt)
        {
            if (dt != null)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    AddErrorMess("第 " + dt.Rows[i][0].ToString() + " 行，第 " + dt.Rows[i][1].ToString() + " 列 数据出错 错误信息：" + dt.Rows[i][2].ToString());
                }
            }
        }

        //protected void btnDowdLoadTemplate_Click(object sender, EventArgs e)
        //{
        //    #region 代码实现

        //    #endregion 代码实现
        //}

        protected void ImBtn_pasteadd_Click(object sender, EventArgs e)
        {

        }

        protected void ShowDBSourceWin_Button_Click(object sender, EventArgs e)
        {
            //string  strReturn = Window.showModalDialog("frame.htm", "ConfigDataSource.aspx", "font-size:10px;dialogWidth:650px;dialogHeight:560px;status=no;center=yes;resizable=no;");
            Response.Redirect("ConfigDataSource.aspx");
        }
        /// <summary>
        /// 保存修改后的单条数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ImBtn_save_Click(object sender, System.EventArgs e)
        {
            DataSave();
        }
      
        protected void FpSpread1_UpdateCommand(object sender, SpreadCommandEventArgs e)
        {

        }

        protected void btnTestIn_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Views/SJCJTEXT/SJCJTextTest.aspx");	
        }

       
    }
}
